/*
 *  Copyright © 2017-2018 Sharder Foundation.
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  version 2 as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, you can visit it at:
 *  https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
 *
 *  This software uses third party libraries and open-source programs,
 *  distributed under licenses described in 3RD-PARTY-LICENSES.
 *
 */

package org.conch.tools;

import io.github.novacrypto.bip39.MnemonicGenerator;
import io.github.novacrypto.bip39.Words;
import io.github.novacrypto.bip39.wordlists.English;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.security.SecureRandom;
import java.util.Random;

/**
 * Generate a random, unique password for the user
 * @author bubai
 * @date 2018/3/24
 */
public class PassPhraseGenerator {

    private static Logger logger = LoggerFactory.getLogger(PassPhraseGenerator.class);

    /**
     * makeRandomSecretPhrase from ascii code combination
     * @return String random secretphrase
     */
    public static String makeRandomSecretPhrase() {
        // use all ascii chars and symbols from '!' (33) to '~' (126)
        final byte start = 33;
        final byte end = 127;
        Random random = new SecureRandom();
        byte[] bytes = new byte[64];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte)(random.nextInt(end - start) + start);
        }
        return new String(bytes, Charset.forName("UTF-8"));
    }

    /**
     * MnemonicWords can be generated by BIP39 implements(such as https://github.com/NovaCrypto/BIP39)
     */
    public static String makeMnemonicWords() {
        StringBuilder sb = new StringBuilder();
        byte[] entropy = new byte[Words.TWELVE.byteLength()];
        new SecureRandom().nextBytes(entropy);
        new MnemonicGenerator(English.INSTANCE)
                .createMnemonic(entropy, sb::append);
        final String mnemonic = sb.toString();
        return mnemonic;
    }

}
